<?php
//by willson 105328468@qq.com 2014/10/11
//index page interface

class message extends core {

	public function __construct() {
		parent::__construct();
	}

	//消息
	public function index() {
        if (!$this->member_id) script('请先登录账号', 'wap.php?tpl=login');
		$message_type = (isset($_GET['message_type']) && trim($_GET['message_type'])) ? intval($_GET['message_type']) : '';
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;

		//by ajsong 20151102 如果没有登录即返回空数据
		if ($this->member_id<=0) success(null);
		$where  = '';
		if ($message_type) $where .= " AND message_type='{$message_type}'";

		if (isMobile()){
            $sql = "SELECT * FROM {$this->tbp}message
			WHERE member_id='{$this->member_id}' {$where} ORDER BY id DESC LIMIT {$offset}, {$pagesize}";
            $messages = $this->db->get_results($sql);
        }else{
            $messages = SQL::share('message')->where("member_id='{$this->member_id}'{$where}")->order('id DESC')->isezr()
                ->limit(0, 10)->find();
        }
        $nav = '';

		if ($messages) {
            $nav = $this->ezr->get_navigation();
			foreach ($messages as $k=>$message) {
				//$messages[$k]->add_time = get_time_word($message->add_time);
				$messages[$k]->add_time = date("Y-m-d H:i:s", $message->add_time);
			}
		}
		//$sql = "UPDATE xfb_message SET readed=1 WHERE member_id='{$this->member_id}'";
		//$this->db->query($sql);
        //增加PC需要的内容
        if (!isMobile()){
            //头像
            $sql = "SELECT avatar FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $avatar = $this->db->get_row($sql);
            //名称
            $sql = "SELECT nick_name FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $nick_name = $this->db->get_row($sql);
            success(array('messages'=>$messages, 'avatar'=>$avatar , 'nick_name'=>$nick_name, 'page'=>$nav));
        }else{
            success($messages);
        }

	}

	//阅读消息
	public function read() {
		$id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		$sql = "UPDATE {$this->tbp}message SET readed=1 WHERE member_id='{$this->member_id}' AND id='{$id}'";
		$this->db->query($sql);
		success("ok");
	}

	//删除消息
	public function delete() {
		$id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		$sql = "DELETE FROM {$this->tbp}message WHERE id='{$id}' AND member_id='{$this->member_id}'";
		//error($sql);
		$this->db->query($sql);
		success("ok");
	}

}
